package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"github.com/opentracing/opentracing-go"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"jaeger-demo/client/middle"
	"jaeger-demo/common"
	"jaeger-demo/otgrpc"
	"jaeger-demo/proto"
	"time"
)

func main() {
	r := gin.Default()
	r.Use(middle.TrancerMiddleware)

	r.GET("/index", func(c *gin.Context) {
		time.Sleep(1 * time.Second)
		// 第一步：连接服务端

		// 从ctx中取出tracer,放入到拦截器中
		tracer, _ := c.Get("tracer")
		tracerPath := tracer.(opentracing.Tracer)

		// 负载均衡
		conn, err := grpc.Dial(
			fmt.Sprintf("consul://%s/grpc_test?wait=14s&tag=lqz", common.ConsulAddr),
			grpc.WithTransportCredentials(insecure.NewCredentials()),
			grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
			grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(tracerPath)),
		)

		if err != nil {
			fmt.Println(err)
			c.JSON(200, "连接grpc服务异常")
		}

		//defer 关闭
		defer conn.Close()
		// 第二步：创建客户端调用
		client := proto.NewGreeterClient(conn)
		// 因为每次请求都是一个新的span,取出父span,放入ctx中
		startSpan, _ := c.Get("startSpan")
		parentSpan := startSpan.(opentracing.Span)
		// 这样放进去，在 otgrpc 中源码中通过opentracing.SpanFromContext(ctx)取出开，取到父span
		ctx := opentracing.ContextWithSpan(context.Background(), parentSpan)
		resp, err := client.SayHello(ctx, &proto.HelloRequest{
			Name: "lqz",
			Age:  19,
		})
		if err != nil {
			c.JSON(200, "服务器错误")
		}
		c.JSON(200, resp.Reply)
	})

	r.GET("/index2", func(c *gin.Context) {
		time.Sleep(1 * time.Second)
		// 第一步：连接服务端
		// 从ctx中取出tracer,放入到拦截器中
		tracer, _ := c.Get("tracer")
		tracerPath := tracer.(opentracing.Tracer)

		// 负载均衡
		conn, err := grpc.Dial(
			fmt.Sprintf("consul://%s/grpc_test?wait=14s&tag=lqz", common.ConsulAddr),
			grpc.WithTransportCredentials(insecure.NewCredentials()),
			grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
			grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(tracerPath)),
		)

		if err != nil {
			fmt.Println(err)
			c.JSON(200, "连接grpc服务异常")
		}

		//defer 关闭
		defer conn.Close()

		// 第二步：创建客户端调用
		client := proto.NewGreeterClient(conn)
		// 因为每次请求都是一个新的span,取出父span,放入ctx中
		startSpan, _ := c.Get("startSpan")
		parentSpan := startSpan.(opentracing.Span)
		// 这样放进去，在otgrpc中源码中通过opentracing.SpanFromContext(ctx)取出开，取到父span
		ctx := opentracing.ContextWithSpan(context.Background(), parentSpan)
		resp, err := client.SayHello(ctx, &proto.HelloRequest{
			Name: "lqz",
			Age:  19,
		})
		if err != nil {
			c.JSON(200, "服务器错误")
		}
		c.JSON(200, resp.Reply)
	})

	r.GET("/index3", func(c *gin.Context) {
		time.Sleep(1 * time.Second)
		// 第一步：连接服务端

		// 从ctx中取出tracer,放入到拦截器中
		tracer, _ := c.Get("tracer")
		tracerPath := tracer.(opentracing.Tracer)

		// 负载均衡
		conn, err := grpc.Dial(
			fmt.Sprintf("consul://%s/grpc_test?wait=14s&tag=lqz", common.ConsulAddr),
			grpc.WithTransportCredentials(insecure.NewCredentials()),
			grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
			grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(tracerPath)),
		)

		if err != nil {
			fmt.Println(err)
			c.JSON(200, "连接grpc服务异常")
		}

		//defer 关闭
		defer conn.Close()

		// 第二步：创建客户端调用
		client := proto.NewGreeterClient(conn)
		// 因为每次请求都是一个新的span,取出父span,放入ctx中
		startSpan, _ := c.Get("startSpan")
		parentSpan := startSpan.(opentracing.Span)
		// 这样放进去，在 otgrpc 中源码中通过opentracing.SpanFromContext(ctx)取出开，取到父span
		ctx := opentracing.ContextWithSpan(context.Background(), parentSpan)
		resp, err := client.SayHello(ctx, &proto.HelloRequest{
			Name: "lqz",
			Age:  19,
		})
		if err != nil {
			c.JSON(200, "服务器错误")
		}
		c.JSON(200, resp.Reply)
	})

	err := r.Run(":8090")
	if err != nil {
		fmt.Println("服务器启动失败！")
	}
}
